<?php
/**
 * @abstract :
 * 		Guest will have same rights as an registered but unactivated user
 * 		table 'hvn.permissions' has roleid : 0 = anonymous, 1 = admin (super admin), 2 = registered user
 *  TODO:
 *  1. Individual
	2. Company
	- User `status` still integer:
	0 = unactivated
	1 = registered (normal)
	2 = upgrading-to-level1 (trusted = registered company)
	3 = level 1 (trusted)
	4 = upgrading-to-level2 (silver)
	5 = level 2 (silver)
	6 = upgrading-to-level3 (golden)
	7 = level 3
 */
class User_AccountController extends Clu_Controller_Action_Master
{ 

	public $m, $mRole; //model
 
	public function init()
	{
		//require_once  (APP_PATH.'/modules/place/Model/Place.php');
		//require_once  (APP_PATH.'/modules/comment/Form/Comment.php');
		//require_once  (APP_PATH.'/modules/comment/Model/Comment.php');
		$this->m = new user_Model_User();
		$this->mComment = new comment_Model_Service();
		$this->mRole = new user_Model_Role();
		parent::init();
	}
	/**
	 * @abstract : Once registered, assign the user to the Anonymous roles
	 * Once activated, assign the registered user role
	 * @see activateAction
	 */ 
    public function registerAction()
    {
    	$this->viewParams['form'] = new user_Form_Register(); 
    	$this->viewParams['form']->cluBuild();
        if ($this->getRequest()->isPost())
        {
            if ($this->viewParams['form']->isValid($_POST))
            {
            	$data = $this->viewParams['form']->getValues();
            	
                if (!$userId = $this->m->insertRaw($data))
                {
                	$this->renderError(null,t(416));
                	return;
                }
                else
                {
                	//Log user in once the user is registered
                    $auth = Zend_Auth::getInstance();
                    $sess = new Zend_Session_Namespace(CLU_NS);
                    $values['name'] = $this->getRequest()->getParam('name');
                    $values['pass'] = $this->getRequest()->getParam('pass');
      
                	if ($this->authenticate($values, $auth, 'login'))
                	{
                		if (!Zend_Registry::get('configuration')->development)
							$this->sendRegistrationMail($userId);
						$this->_helper->redirector->gotoUrl($sess->viewLang .'/user/account/edit-profile?id='.$userId.'&j=1'); //todo
    	                return;
                	}
                }
            }
        }
    }

	public function sendRegistrationMail($userId)
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
		$u = $this->m->findByPrimary($userId);
		$this->viewParams['userid'] = $userId;
		$this->viewParams['username'] = $u->name;
		$this->viewParams['activation_code'] = $u->activation_code; 
		$this->viewParams['url'] = Zend_Registry::get('configuration')->general->url;
		$subject = 'Welcome to herevietnam.vn';
		$mailBody = "<b> Dear".$this->viewParams['username']."</b>,
		Thank you for registering!
		Before we can activate your account one last step must be taken to complete your registration.
		Please note - you must complete this last step to become a registered member. You will only need to visit this URL once to activate your account.
		To complete your registration, please visit this URL:<br/>
		Click : <a href='http://".$this->viewParams['url']."/vi/activate?userid=".$this->viewParams['userid']."&acode=".$this->viewParams['activation_code']."'>
		http://".$this->viewParams['url']."/vi/activate?userid=".$this->viewParams['userid']."&acode=".$this->viewParams['activation_code']."
		</a>Please be sure not to add extra spaces. You will need to type in your username and activation number on the page that appears when you visit the URL.
		<br/>Your Username is: ".$this->viewParams['username']."  Your Activation ID is: ".$this->viewParams['activation_code']."";
		//$mailBody =  $this->view->render('/modules/user/views/scripts/commonTheme/commonLang/common/mail_activate_user.phtml');
		$mailer = new Clu_Mail_HvnMailer();
		$mailer->sendMail($u->mail, $subject, $mailBody);		
	}
	/**
	 * @abstract : Once activated, assign the registered user role
	 * @see activateAction
	 */ 
	public function activateAction()
	{
		$getParams = $this->_request->getParams();
        if (isset($getParams['userid']) && isset($getParams['acode'])) //user clicked on an activation link
		{	
            // activate the user if the activation code is valid
            $u = $this->m->findByPrimary($getParams['userid']);
            if ($u)
            {               
                if ($u->status != 0)
                    $this->viewParams['userAlreadyActive'] = true;
                else if ($u->status == 0 && $u->activation_code == $getParams['acode']
                					&& $this->m->activateUser($u) )
                $this->viewParams['activatedOK'] = true;
            	//Log user in once the user is registered
                $auth = Zend_Auth::getInstance();
                $sess = new Zend_Session_Namespace(CLU_NS);
                $values['name'] = $u->name;
                $values['pass'] = $u->pass;
            	if ($this->authenticate($values, $auth, 'activate'))
            	{
                    //$this->_forward('register', 'account', 'user', array('justRegistered' => true)); //todo
                    //$this->_forward('index', 'index', 'home'); //todo
                    $this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('module'=>SITE, 'action' => 'home'), 'nocontroller'));
                    return;
            	}
            }
            //$this->renderToHolder('account/activation-results.phtml', false, null, 4, 2);
            return;
		}
	}
	
	/*
	 * view home user
	 */
	public function viewAction()
	{
		//Do nothing 
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->getUserData($id))
        {
            $this->renderError(null,t(406));
            return;
        }
        
        $this->paramsForWidgets['id'] = $id;
//        $this->paramsForWidgets['type'] = $u->type;
		//$this->paramsForWidgets['currentTab'] = "view-account";
        
        //following code should be moved into widgetcontroller
        
		$auth = Zend_Auth::getInstance();
       	$uIdentity = $auth->getIdentity();
       	if(isset($uIdentity)){
			$visitorId = $uIdentity->id;
			$this->paramsForWidgets['visitorId'] = $visitorId;
			$visitor_id = $this->m->getVisitorUser($visitorId);
			if($visitorId != $id)
			{
				$this->m->insertDbAfterView($id, $visitorId);
			}
       	}
        $this->viewParams['u'] = $u;
        $this->viewParams['activity'] = "";
        $this->viewParams['content_id'] = $id;
        $this->viewParams['content_type'] = 'user';
        //paramsForWidgets
        $this->paramsForWidgets['u'] = $u;
        $this->paramsForWidgets['content_id'] = $id;
        $this->paramsForWidgets['content_type'] = 'user';
    }
	
    /*
     * When viewing other people's profile
     */
	public function viewProfileAction()
	{
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->getUserData($id))
        {
            $this->renderError(null,t(406));
            return;
        }
        $this->paramsForWidgets['id'] = $id;
//        $this->paramsForWidgets['type'] = $u->type;
        $this->viewParams['u'] = $u;
	}
	
	public function editProfileAction()
	{
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->findByPrimary($id))
        {              
           $this->renderError(null,t(504));
            return;
        }
        //now check if either this is the logged in user
        //or an user admin
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($sess->userId != $id && strpos ($sess->userPermissions, 'administer user') === false)
		{
    	    $this->renderError(null,t(504));
            return;
		}                
        
        //everything's fine. Continue editing
        if ($this->_request->getParam('j') == 1)
        {
        	$this->viewParams['justRegistered'] = true;
        }
        
        $this->viewParams['form'] = new user_Form_Edit();
//        $this->viewParams['form']->cluBuild(array('type' => $u->type, 'view' => $this->view));
        
        //$actionUrl = $this->view->hvnUrl(array('module' => 'user', 'action'=>'edit-profile'), 'account');
        $actionUrl = $this->view->hvnUrl(array('module' => 'user', 'action'=>'edit-profile', 'controller' => 'account'));
        $this->viewParams['form']->cluBuild(array('action' => 'edit-profile', 'action_url' => $actionUrl, 'type' => $u->type));
        
        if (!$this->_request->isPost())
            $this->viewParams['form']->populate($u->toArray());

        else if ($this->viewParams['form']->isValid($_POST))
        {	
            if ($this->m->saveRaw($u, $this->viewParams['form']->getValues(), $id, false))
            {
            	$this->viewParams['successMessage'] = t(407);
            }
            else 
                $this->viewParams['errorMessage'] = t(408);
        }
        else
        	$this->viewParams['errorMessage'] = t(71);
		
        $this->viewParams['id'] = $id;
        $this->viewParams['type'] = $u->type;
        $this->viewParams['u'] = $u;
        $this->paramsForWidgets['id'] = $id;
	}
	
	/**
	 * 
	 * @abstract : Once logged in, the following info is stored to Session for later use
	 * 			userRoles: List of roles for users "1,2,5"
	 * 			userPermissions: List of permissions: "read article, create article...."
	 * 			userTheme
	 * 			viewLang
	 * 			blockList -> handed to Block Module to compute
	 * @see $this->logoutAction();
	 */
	
    public function loginAction()
    {
        $auth = Zend_Auth::getInstance();
        $sess = new Zend_Session_Namespace(CLU_NS);
        
        /*
         * OpenId
         */
        /*
        $status = "";
		if ((isset($_POST['openid_action']) &&
		     $_POST['openid_action'] == "login" &&
		     !empty($_POST['openid_identifier'])) ||
		    isset($_GET['openid_mode'])) {
		    $adapter = new Clu_Auth_Adapter_OpenId(@$_POST['openid_identifier']);
		    $result = $auth->authenticate($adapter);
		    die_a($result);
		    if ($result->isValid()) {
		        Zend_OpenId::redirect(Zend_OpenId::selfURL());
		    } else {
		        $auth->clearIdentity();
		        foreach ($result->getMessages() as $message) {
		            $status .= "$message<br>\n";
		        }
		    }
		    
		} else if ($auth->hasIdentity()) {
		    if (isset($_POST['openid_action']) &&
		        $_POST['openid_action'] == "logout") {
		        $auth->clearIdentity();
		    } else {
		        $status = "You are logged in as " . $auth->getIdentity() . "<br>\n";
		    }
		}
		
		$this->viewParams['status'] = htmlspecialchars($status);        
		*/
        if ($auth->hasIdentity()) {

        	if ($this->_request->getParam('forceLogout') == 1) //sometimes user wants to login as a different user
        	{
        		//back to anonymous
                Zend_Auth::getInstance()->clearIdentity();
                $sess->userPermissions = Zend_Registry::get('configuration')->anon->perms; //?
        	}
        	
            else
            {
            	if ($this->_request->isXmlHttpRequest())
        		{
	        			//generate json
	        			//sendJson
	        			$ret['success'] = false;
	        			$ret['errorMessage'] = t(409);
	        			$this->_helper->json->sendJson($ret);
	        			return;
        		}
            
               //$this->renderToHolder('account/already-loggedin.phtml', false, null, 4, 2);
               $this->viewParams['notificationType'] = "already-logged-in";
               $this->presenceIdentifier = 2;//already logged in
               return;
            }
        }
        else
        {
	        $this->viewParams['form'] = new user_Form_Login();
	        $this->viewParams['form']->cluBuild();
		    //present the login form. First time 
	        if ($this->_request->isGet())
	        {
	        	return;
	        }
	        else  //either POST Or XMLHTTP
	        {
	        	$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
				//$referer=parse_url($referer);
	        	//make sure form is valid first
	        	if (!$this->viewParams['form']->isValid($_POST))
	        	{
	        		if ($this->_request->isPost())
	        		{
						$this->viewParams['errorMessage'] = t(410);
	        		}
	        		else if ($this->_request->isXmlHttpRequest())
	        		{
		        			$ret['success'] = false;
		        			$ret['errorMessage'] = t(410);
		        			$this->_helper->json->sendJson($ret); exit();
	        		}
	        	}
	        	else //form is now valid, 
	        	{
			        $values = $this->viewParams['form']->getValues();
				    $userIsValid = $this->authenticate($values, $auth, 'login');
				    $ret = array();
	        		if ($userIsValid)
	        		{
		        		if ($this->_request->isXmlHttpRequest())
		        		{
		        			$ret['success'] = true;
		        			$ret['url'] = $referer;
		        			$this->_helper->json->sendJson($ret); exit();
		        		}
		        		else if ($this->_request->isPost())
		        		{
		        			$this->_helper->redirector->gotoUrl($referer);
		        			/*$this->viewParams['operation'] = t(411);
						    $this->viewParams['notificationType'] = "login-success";
						    $this->presenceIdentifier = 2; //go to a notification template
						    */
					        return;
		        		}
		        		
	        		}
	        		else //failed logging in
	        		{
	        			$ret['url'] = $this->view->hvnUrl(array('action' => 'register'),'account');
	        			if($this->_request->isXmlHttpRequest())
	        			{
	        				//$ret['success'] = false;
	        				$this->viewParams['errorMessage'] = t(410);
		        			$this->_helper->json->sendJson($ret);
	        			}
	        			else if($this->_request->isPost())
	        			{
	        				$this->_helper->redirector->gotoUrl($ret['url']);
	        				/*$this->viewParams['operation'] = t(410);
	        				$this->viewParams['errorMessage'] = t(410);
						    $this->renderError(null,t(410));*/
					        return;
	        			}
	        			
	        		}
	        	}
	        }
        }
       
    }

    
    /**
	 * @abstract A function to wrap the authenticate/log-in action
	 * 		If login credential is valid, then perform some session actions to set user's data to session
	 *	 		and save the Auth object to the Zend_Session_Namespace('Zend_Auth') (Zend's default)
	 * 			and return the Zend_Auth's authentication result 
	 * 		else return false;
	 * @values: array containing ['name'] & ['pass']
	 * @auth: Zend_Auth object
	 * @page: 'activate', 'login' or 'register' are the 3 cases where we want to set logged in status
	 * @sess: Zend_Session_Namespace[CLU_NS] 
	 */ 
    public function authenticate ($values, $auth , $page)
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
        $adapter = new Clu_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        $adapter->setTableName('users');
        $adapter->setIdentityColumn('name');
    	$adapter->setCredentialColumn('pass');
    	        			        
		if ($page === 'activate')
			$adapter->setCredential($values['pass']);
    	if ($page === 'login') //need hashing
        {
        	$adapter->setCredential(
            	hash('SHA256', 'salt' . $values['pass'] . 'pepper'));
        }
        
        $adapter->setIdentity($values['name']);
        $result = $auth->authenticate($adapter);
        		        
        if ($result->isValid()) {
        	//store authentication
            $auth->getStorage()
                 ->write($adapter->getResultRowObject(null, 'pass'));
            
            //write some necessary data to session
        	//$u = new user_Model_User();
        	$uIdentity = $auth->getIdentity();
        	
        	//roles
        	$sess->userRoles = $this->m->getUserRoles($uIdentity->id);
        	//permissions
        	$sess->userPermissions = $this->mRole->getUserPermissionsFromRoleIds($sess->userRoles);
			//theme
        	$sess->userTheme = empty($uIdentity->theme) ? Zend_Registry::get('configuration')->general->defaultTheme:$uIdentity->theme;
        	//viewLang        	
        	$sess->viewLang = $uIdentity->language;
        	$sess->userId = $uIdentity->id;
        	$sess->userName = $uIdentity->name;
        	//Zend_Registry::set('viewLang', $sess->viewLang); //TODO: to be removed
        	//blocks: 
			//reset blocks only. The list of blocks available to user
			//is handled in Block/IndexController/IndexAction
			unset($sess->blockList);
			return $result;
        }
        else
        	return false;
    }    
    
    /**
     * Once logged out, clear all the 
     * 		identity
     * 		session data
     * 
     * @see $this->loginAction();
	 */
    
    public function logoutAction()
    {
    
        Zend_Auth::getInstance()->clearIdentity();
        //TODO: clear all the session data such as block views
        
        $sess = new Zend_Session_Namespace(CLU_NS);
        $sess->userPermissions = Zend_Registry::get('configuration')->anon->perms;
        $sess->userRoles = '0'; //TODO: get the anonymous role here
        $sess->userTheme = Zend_Registry::get('configuration')->general->defaultTheme;//TODO: reset? or not
        $sess->userId = 0;
        unset($sess->userId);
        //set identity = anonymous here
        unset($sess->blockList);
        $backUrl = $this->_request->getParam('backurl');
        //$this->_forward('login');	
        //$this->_helper->redirector->gotoUrl($backUrl);
//        $this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('module'=>'hvn', 'action' => 'home', 'controller' => 'index'), 'nocontroller'));
		$this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('module'=>SITE, 'action' => 'home'), 'nocontroller'));
//        $this->_helper->redirector->gotoUrl($this->view->hvnUrl(array(), 'home1'));
    }    
    
    public function remindPasswordAction()
    {
    	$mail = $this->_request->getParam('mail');
    	if (!$mail)
    	{
    		//$this->renderToHolder('account/remind-password.phtml');
    		return;
    	}
    	//else it is post 
    	$u = $this->m->search(array('mail' => $mail));
    	$paginator = $this->generatePaginator($u, null, null, null, 'Jumping');
	    $u = $paginator->getCurrentItems();
	    $u = $this->findByPrimary($u[0]['id']);
    	$newPass = $this->generatePassword(8);
    	if ($this->m->saveRaw($u, array('pass'=>$newPass),null, false))
    	{
    		//email client
    		//TODO: Fake here
    		$this->viewParams['operation'] = sprintf(t(412),$newPass);
    		//$this->renderToHolder('common/success.phtml');
    	}
    	else
    	{
    		$this->renderError(null,t(504));
            return;
    	}
    		//$this->renderToHolder('common/error.phtml');
    }
    
    /* TODO : move into common.php */
    function generatePassword ($length = 8)
    {
		$password = "";
      	$possible = "0123456789abcdefghjklmnopqrstuvwxyz"; 
        
	    $i = 0; 
    	// add random characters to $password until $length is reached
      	while ($i < $length) { 
    
        // pick a random character from the possible ones
        $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
        if (!strstr($password, $char)) { 
        	$password .= $char;
          	$i++;
        }
      }
    
      return $password;
    }
    
    public function avatarAction()
    {
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->findByPrimary($id))
        {                
            $this->renderError(null,t(504));
            return;
        }
    
        //now check if either this is the logged in user
        //or an user admin
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($sess->userId != $id && strpos ($sess->userPermissions, 'administer user') === false)
		{
	    	    $this->renderError(null,t(504));
	            return;
		}           

		//now continue
		//allowed, now continue
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$form = new user_Form_Avatar();
    	$form->cluBuild($id);
    	$this->viewParams['id'] = $id;
    	$this->viewParams['form'] = $form;
		
    	if($this->_request->isPost())
		{
			$formData = $this->_request->getPost();
			if ($form->isValid($formData)) {
				try {
					$this->postImage($id, true);
				}
				catch (Exception $e)
				{
					$this->viewParams['errorMessage'] = __("Something wrong");
				}
			}
			else
			{
				$form->populate($formData);
			}
		}

		if (file_exists(APP_PATH."/public/ufiles/$id/images/original/avatar/avatar.jpg"))
		{
			$this->viewParams['avatar_image_rand'] = "/public/ufiles/$id/images/%s/avatar/avatar.jpg?". time();
			$this->viewParams['avatar_image'] = APP_PATH."/public/ufiles/$id/images/%s/avatar/avatar.jpg";
		}
		
		$this->paramsForWidgets['id'] = $id;
//        $this->paramsForWidgets['type'] = $u->type;
//        $this->paramsForWidgets['currentTab'] = "avatar";
    } 
    
    public function changePassAction()
    {
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->findByPrimary($id))
        {                
            $this->renderError(null,t(504));
            return;
        }
        //now check if either this is the logged in user
        //or an user admin
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($sess->userId != $id && strpos ($sess->userPermissions, 'administer user') === false)
		{
	    	    $this->renderError(null,t(504));
	            return;
		}        
    	
	//allowed, now continue
    	$this->viewParams['form'] = new user_Form_ChangePass();
    	$this->viewParams['form']->cluBuild($id);
    	$this->viewParams['id'] = $id;
		
    	if($this->_request->isPost())
		{
			$formData = $this->_request->getPost();
			if ($this->viewParams['form']->isValid($formData) && $formData['pass'] == $formData['pass2']) {
				try {
					//$this->postImage($id, true);
					//TODO : change pass
					$u->pass = hash('SHA256', 'salt' . $formData['pass'] . 'pepper');
					$u->save();
					$this->viewParams['successMessage'] = t(417);
				}
				catch (Exception $e)
				{
					$this->viewParams['errorMessage'] = t(416);
				}
			}
			else
				$this->viewParams['errorMessage'] = t(415);
//			else
//			{
//				$form->populate($formData);
//			}
		}
		$this->paramsForWidgets['id'] = $id;
//        $this->paramsForWidgets['type'] = $u->type;
//        $this->paramsForWidgets['currentTab'] = "change-pass";
    } 
        
    public function upgradeAccountAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->findByPrimary($id))
        {                
            $this->renderError(null,t(504));
            return;
        }
        //now check if either this is the logged in user
        //or an user admin
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($sess->userId != $id && strpos ($sess->userPermissions, 'administer user') === false)
		{
    	    $this->renderError(null,t(504));
            return;
		}     
    	
		//allowed, now continue
    	
    	$this->viewParams['form'] = new user_Form_UpgradeAccount();
    	$this->viewParams['form']->cluBuild($id);
    	$this->viewParams['id'] = $id;
		
    	if($this->_request->isPost())
		{
			$formData = $this->_request->getPost();
  		    if ($this->viewParams['form']->isValid($formData)) {
				try {
					$this->m->saveRaw($u, $formData, $id, false);
					//$this->view->successMessage = t(476);
				}
				catch (Exception $e)
				{
					$this->viewParamss['errorMessage'] = t(416);
				}
			}
			else
				$this->viewParams['errorMessage'] = t(415);
		}
		
		$this->paramsForWidgets['id'] = $id;
    }     
    
	public function deleteUserAction()
	{
		$id = $this->_request->getParam('id');
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($this->_request->isXmlHttpRequest())
		{
			$ret = array();
			if (strpos ($sess->userPermissions, 'administer user') === false)
			{
				$ret['success'] = false;
				$ret['message'] = t(414);
				$this->_helper->json->sendJson($ret);
				exit();
			}
			
			if ($this->m->deleteByPrimary(array($id)))
            {
            	$ret['success'] = true;
            }
            else
            {
            	$ret['success'] = false;
            	$ret['message'] = t(510);
            }	 
			$this->_helper->json->sendJson($ret);
		}
	}	
    
	public function postImage($userId, $createWM)
	{
		//require_once APP_PATH."/library/common.php";
		$watermarkDir = APP_PATH."/public/watermark/";
		
		//see generate_image_copies() @ /library/common.php
		$ustoreDir = APP_PATH."/public/ustore/$userId/images/original/avatar/";
		if (!file_exists($ustoreDir))
			mkdir($ustoreDir, 0777 , true);

		$ufilesDir = APP_PATH."/public/ufiles/$userId/images/original/avatar/" ; //just for avatar
		if (!file_exists($ufilesDir))
			mkdir($ufilesDir, 0777  , true);
		
			
		$adapter= new Zend_File_Transfer_Adapter_Http();

		/* TODO: WILL BE USED FOR GALLERY, NOT AVATAR 
		$extension_path = pathinfo($_FILES['file_upload']['name']);

		$fileName = $extension_path['filename'];
		$extension =  $extension_path['extension'];
		
		if (empty($extension))
		{		
			$mimeType = $_FILES['file_upload']['type'];
			$extension = explode('/', $mimeType);
		}

		$saneFileName = SanitizeFileName($fileName);

		$i = 1;
		while(file_exists($ustoreDir. $saneFileName . "." . $extension))
		{
			$saneFileName = $saneFileName . "_" .$i;
			$i++;
		}

		$originalFilename = $ustoreDir. $saneFileName . "." . $extension;
		*/
		$saneFileName = "avatar.jpg";
		$originalFilename = $ustoreDir. "avatar.jpg";
		
		try 
		{
			$adapter->addFilter('Rename', array('target' => $originalFilename, 'overwrite' => true));
			$adapter->receive();
			copy ($originalFilename, $ufilesDir. "avatar.jpg" );
		}
		catch (Zend_File_Transfer_Exception $e) 
		{
		     $e->getMessage();
		}
		chmod($originalFilename, 0666);
		
		//generate_image_copies($ustoreDir, $newfileName, $watermarkDir, $configSize, $configSizeInPixel, $userId, $createWM);
		//generate_image_copies("ustore", $sServerDir, $sFileName, HVN_APP_PATH . '/public/watermark/',
	    //                                    null, null,  $_SESSION['user_id'], true);
		$configSizes = array("xxsmall", "xsmall", "small", "medium");
		$configSizesInPixel = array("30", "75", "100", "260");
		
		//delete current images first
		foreach ($configSizes as $size)
		{
			if (file_exists(APP_PATH."/public/ufiles/$userId/images/$size/avatar/avatar.jpg"))
				unlink(APP_PATH."/public/ufiles/$userId/images/$size/avatar/avatar.jpg");
		}
    	//generate_image_copies ("ustore", $ustoreDir, $saneFileName . "." . $extension, $watermarkDir, $configSizes, $configSizesInPixel, $userId, false);
		generate_image_copies ("ustore", $ustoreDir, $saneFileName, $watermarkDir, $configSizes, $configSizesInPixel, $userId, false);    	
	                               
	}
	
	public function billingInfoAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->findByPrimary($id))
        {                
            $this->renderError(null,t(504));
            return;
        }
        //now check if either this is the logged in user
        //or an user admin
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($sess->userId != $id && strpos ($sess->userPermissions, 'administer user') === false)
		{
    	    $this->renderError(null,t(504));
            return;
		} 
    	
		//allowed, now continue
    	$number = $this->_request->getParam('number');
    	$this->viewParams['form'] = new user_Form_BillingInfo();
    	$this->viewParams['form']->cluBuild(array('id' => $id, 'number' => $number));
    	$formName = 'Edit-Billing';
    	$this->viewParams['id'] = $id;
		if(!empty($u->billing))
		{
	        $a = unserialize($u->billing);
	        if(!isset($number))
	        {
		        foreach($a['billing'] as $k =>$v)
		        {
		        	$dataDisplay[$k] = unserialize($v);
		        }
		        $this->viewParams['dataDisplay'] = $dataDisplay;
	        }
	        else
	        {
	        	foreach($a['billing'] as $k =>$v)
		        {
		        	$dataDisplay = unserialize($v);
		        }
		        $this->viewParams['account_type'] = $dataDisplay['account_type'];
		        $a['account_type'] = $dataDisplay['account_type'];
		        $a['number'] = $number;
				$this->viewParams['form']->populateForm($formName, $a);
	        }
			
		}       
		
    	if($this->_request->isPost())
		{
			$formData = $this->_request->getPost();
			if(isset($number))
				$formData['number'] = $number;
  		    if ($this->viewParams['form']->isValid($formData)) {
				try {
					$this->m->saveBillingInfo($u, $formData);
					//$this->view->successMessage = t(476);
				}
				catch (Exception $e)
				{
					$this->viewParams['errorMessage'] = t(416);
				}
			}
			else
				$this->viewParams['errorMessage'] = t(415);

	    	$this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('action' => 'billing-info', 'module' => 'user'), 'account') .	'?id='.$id);
		}
		
		$this->paramsForWidgets['id'] = $id;
//        $this->paramsForWidgets['type'] = $u->type;
//        $this->paramsForWidgets['currentTab'] = "billing-info";
		
		return;
    }     
	
	public function deleteBillingInfoAction()
	{
		$sess = new Zend_Session_Namespace(CLU_NS);
		$id = $this->_request->getParam("id");
		if (!$u = $this->m->findByPrimary($id))
        {                
            $this->renderError(null,t(504));
        	return;
        }
        
		//now check if either this is the logged in user
        //or an user admin
		$sess = new Zend_Session_Namespace(CLU_NS);
		if ($sess->userId != $id && strpos ($sess->userPermissions, 'administer user') === false)
		{
    	    $this->renderError(null,t(504));
            return;
		}         
		
		$number = $this->_request->getParam('number');
		$this->m->deleteBillingInfo($u, $number);
		$this->_helper->redirector->gotoUrl($this->view->hvnUrl(array('action' => 'billing-info', 'module' => 'user'), 'account') .	'?id='.$id);
		return;
	}
	
	public function changeAccountTypeAction()
    {
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->findByPrimary($id))
        {                
         	$this->renderError(null,t(504));
        	return;
        }
        //now check if either this is the logged in user
        //or an user admin
		if ($sess->userId != $id && strpos ($sess->userPermissions, 'administer user') === false)
		{
    	    $this->renderError(null,t(504));
            return;
		}       
    	
		//allowed, now continue
    	$this->viewParams['form'] = new user_Form_ChangeAccountType();
    	$this->viewParams['form']->cluBuild($id);
    	$this->viewParams['id'] = $id;
		
    	if($this->_request->isPost())
		{
			$formData = $this->_request->getPost();
  		    if ($this->viewParams['form']->isValid($formData)) {
				try {
					$this->m->saveRaw($u, $formData, $id, false);
					$this->view->successMessage = t(476);
				}
				catch (Exception $e)
				{
					$this->viewParams['errorMessage'] = t(416);
				}
			}
			else
				$this->viewParams['errorMessage'] = t(415);
		}
		
		$this->paramsForWidgets['id'] = $id;
    }     
    
    public function mailboxAction()
    {
    	$id = $this->_request->getParam("id");
    	if (!$u = $this->m->findByPrimary($id))
        {                
            $this->renderError(null,t(504));
            return;
        }
    	
		$sess = new Zend_Session_Namespace(CLU_NS);
		if (!$sess->userId || (strpos ($sess->userPermissions, 'administer pm') == false &&  $sess->userId != $u->id))
		{
			$this->renderError(null, "Not allowed");
			return;
		}
    	//require_once (APP_PATH. "/modules/node/Model/NodeService.php");
    	$this->mService = new node_Model_NodeService();
		$nodeTypeInfo = $this->mService->getNodeTypeInfo("pm");
		$requestData = $this->_request->getParams();
		$tmp = $this->mService->prepareNodeSearchData($requestData, $nodeTypeInfo);
		if (!$tmp['success'])
		{
			$this->renderError(null, $tmp['errorMessage']);
			return;
		}
		$searchData = $tmp['nodeSearchData']; 
		$searchUrl = encode_search_url($searchData, "pm");
		$this->viewParams['searchUrl'] = $searchUrl;
	   	$selectStmt = $this->mService->search($searchData, $nodeTypeInfo);
		$paginator = $this->generatePaginator($selectStmt, $searchData['page'], $searchData['items_per_page'], 7, 'Jumping');
		if (isset($paginator))
		{
	       	$this->viewParams['paginator'] = $paginator;
	       	$mails = $paginator->getCurrentItems();
	       	// having $mails, now render conversations
			$this->viewParams['mails'] = $mails;
			$this->viewParams['conversations'] = array(); //TODO
		}		
		$this->paramsForWidgets['viewer_id'] = $searchData['receiver_id'];
		
		$this->paramsForWidgets['id'] = $id;
//        $this->paramsForWidgets['type'] = $u->type;
        //$this->paramsForWidgets['currentTab'] = "mailbox";
    }
    
    public function readMailAction()
    {
		$sess = new Zend_Session_Namespace(CLU_NS);
		if (!$sess->userId)// || (strpos ($sess->userPermissions, 'administer pm') == false &&  $sess->userId != $data['receiver_id']))
		{
			$this->renderError(null, "Not allowed");
			return;
		}
		
        //require_once (APP_PATH. "/modules/node/Model/NodeService.php");
    	$this->mService = new node_Model_NodeService();
		$nodeTypeInfo = $this->mService->getNodeTypeInfo("pm");
    		//new view the node
		$nodeId = $this->_request->getParam('id');
		$ret = $this->mService->getNodeData($nodeTypeInfo, $nodeId);
		if ($ret['success'])
		{
			$this->viewParams['node'] = $ret['node'];
			$this->mService->updateDbAfterView($nodeTypeInfo, $nodeId);
		}
		$this->paramsForWidgets['viewer_id'] = $ret['node']['receiver_id'];
    }
    
    /*
     * This action accepts a request like 
     * 		view-posts?id=7&content_type=gallery or
     * 		view-posts?id=7&content_type=all or
     *  It will selectively choose the right content type and return a list
     *  to be displayed by a same .phtml if nec.  
     */
    public function viewPostsAction()
    {
    	//user Id
    	$id = $this->_request->getParam('id');
    	if (!$u = $this->m->findByPrimary($id))
        {                
            $this->renderError(null,t(504));
            return;
        }
		$sess = new Zend_Session_Namespace(CLU_NS);
    	$contentType = $this->_request->getParam('content_type');
		if ($contentType == "place")
		{
			//require_once(APP_PATH . "/modules/place/Model/Place.php");
			$model = new place_Model_Place();
		}
		else if ($contentType == "event")
		{
			//require_once(APP_PATH . "/modules/event/Model/Event.php");
			$model = new event_Model_Service();
		}
		//TODO: comments
		else if (in_array($contentType, array("blog", "news", "gallery", "promotion")))
		{
			//contentType being nodeType
			//require_once(APP_PATH . "/modules/node/Model/NodeService.php");
			$model = new node_Model_NodeService();
			$nodeTypeInfo = $model->getNodeTypeInfo($contentType);
		}
		//$row = $model->findNodeByPrimary($nodeTypeInfo, $contentId);
		//now find the content by user id $id
		
		$data = array("poster_id" => $id, "items_perpage" => 10	);
		if ($this->_request->getParam('page'))
			$data['page'] = $this->_request->getParam('page');
		else
			$data['page'] = 1;
		
		if ($contentType == "place" || $contentType == 'event' )
		{
		   	$select = $model->search($data);
		}
		else
		{
			$select = $model->search($data, $nodeTypeInfo);
		}
		$paginator = $this->generatePaginator($select, $data['page'], $data['items_perpage'], 7, 'Jumping');
        $searchUrl = encode_search_url($data, $contentType);
		//$this->viewParams['searchUrl'] = $searchUrl;
		$this->viewParams['searchUrl'] = 
			"http://" . SITE_URL . $this->view->hvnUrl(array('action' => 'view-posts'),'account') . "?id=$id&content_type=$contentType&$searchUrl";
		//die($searchUrl);
		//die($this->viewParams['searchUrl']);
	    //the results
    	if(isset($paginator))
        {	
	       	$this->viewParams['paginator'] = $paginator;
			$this->viewParams['items'] = $paginator->getCurrentItems();
			//get articles
			//require_once(APP_PATH . "/modules/article/Model/Article.php");
			$articleList = array();
			$mArticle = new article_Model_Service();
			foreach ($this->viewParams['items'] as $p)
			{
				$articleList[$p['id']] = $mArticle->getArticleData($p['article_id']);
			}
			$this->viewParams['aList'] = $articleList;
       	}
		$this->paramsForWidgets['id'] = $id;
		$this->viewParams['id'] = $id;
		$this->viewParams['contentType'] = $contentType;
    }
	/*
	 * update role for user is company
	public function searchUserStatusAction()
    {
    	$this->viewParams['results'] =$this->m->changeUserStatusSearch();
    	foreach($this->viewParams['results'] as $val)
    	{
    		$roleList[$val['id']] = $this->m->getUserRoles($val['id']);
			$roleName[$val['id']] = $this->mRole->getUserPermissionsFromRoleIds($roleList[$val['id']]);	    	
    	}
	  	$this->viewParams['roles'] = $roleName;
    }
    */
    public function activateRoleForUserCompanyAction()
    {
    	$data = $this->_request->getParams();
    	$this->m->updateChangeStatusForUser($data['id'], $data);
    }  
    
    public function listProductAction()
    {
    	$this->paramsForWidgets['id'] = $this->_request->getParam('id');
    }
}	
